package com.huarui.initialItem.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.service.BaseService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.initial.model.Initial;
import com.huarui.initial.service.InitialService;
import com.huarui.initial.util.InitialErrorsEnum;
import com.huarui.initial.util.InitialItemErrors;
import com.huarui.initial.util.InitialUtil;
import com.huarui.initialItem.dao.IinitialItemDao;
import com.huarui.initialItem.model.InitialItem;
import com.huarui.part.model.Part;
import com.huarui.part.service.PartService;
import com.huarui.user.model.SessionMessage;

public class InitialItemService extends BaseService {
	private final static Logger logger = Logger.getLogger(InitialItemService.class);
	private PartService partService;
	private InitialService initialService;
	
	private IinitialItemDao getDao() {
		return (IinitialItemDao) dao;
	}

	@SuppressWarnings("unchecked")
	public ListModel getInitialItemsByInitialId(Map map, ListModel lm) {
		Integer total = this.getDao().pagingItemsCountByInitialId(map);
		lm.setTotal(total);
		map.put("listModel", lm);
		List result = this.getDao().pagingItemsByInitialId(map);
		lm.setResult(result);
		return lm;
	}
	@SuppressWarnings("unchecked")
	public ListModel query(Map map, ListModel lm) {
		Integer total = this.getDao().queryCodeCountByInitialId(map);
		lm.setTotal(total);
		map.put("listModel", lm);
		List result = this.getDao().queryCodeListByInitialId(map);
		lm.setResult(result);
		return lm;
	}
	@SuppressWarnings("unchecked")
	public ListModel findAllItemsByCondition(Map<String,Object> map, ListModel lm) {
		Integer total = this.getDao().findAllItemsCountByCondition(map);
		lm.setTotal(total);
		map.put("listModel", lm);
		List result = this.getDao().findAllItemsByCondition(map);
		lm.setResult(result);
		return lm;
	}




	@SuppressWarnings("unchecked")
	public Map<String,Object> deleteInitialItemById(final Integer id,final Integer initialId,final SessionMessage sm){
		Map<String,Object> resultMap=(Map<String, Object>) transactionTemplate.execute(new TransactionCallback() {
			Map<String,Object> resultMap=new HashMap<String, Object>();
			@Override
			public Object doInTransaction(TransactionStatus status) {
				Initial initial=null;
				try {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", initialId);
					map.put("companyId", sm.getCompanyId());
					map.put("isLock", true);
					initial = (Initial) initialService.getById(map);
					if (initial == null) {
						resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(),"该期初单据不存在或无权删除该单据");
						status.isRollbackOnly();
						return resultMap;
					}
					map.clear();
					map.put("id", id);
					map.put("companyId", sm.getCompanyId());
					InitialItem initialItem = (InitialItem) getDao().getById(map);
					if(initial.getAmount()==null){
						initial.setAmount(new BigDecimal(0));
					}else if(initialItem.getCostAmount()==null){
						initialItem.setCostAmount(new BigDecimal(0));
					}
					initial.setAmount(initial.getAmount().subtract(initialItem.getCostAmount()));
					getDao().deleteById(id);
					initialService.update(initial);
					//resultMap.put("initial", initial);
				} catch (Exception e) {
					logger.error("删除期初单明细错误"+e.toString());
					resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(),"该期初单据不存在或无权删除该单据");
					status.isRollbackOnly();
					return resultMap;
				}
				resultMap.put("amount", initial.getAmount());
				resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(),InitialErrorsEnum.RESULT_TYPE_SUCCESS.getMsg());
				return resultMap;
			}
		});
		return resultMap;
	}
	@SuppressWarnings("unchecked")
	public Map<String,Object> saveInitialItem(final InitialItem initialItemTemp,
			final Initial initial,final SessionMessage sm) {	
		final Map<String,Object> resultMap=new HashMap<String, Object>();
		transactionTemplate.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				Map map = new HashMap();
				boolean isRetInitial=false;
				try{
					Initial initialNew=null;
					if(initial.getId()==null){	
						initialNew=initialService.createInitial(sm);
						isRetInitial=true;
					}else{
						map.put("id", initial.getId());
						map.put("companyId", sm.getCompanyId());
						map.put("isLock", true);
						initialNew=(Initial) initialService.getById(map);
						if(initialNew==null){
							resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(), InitialErrorsEnum.ERROR_MSG_RECORD_DELETE.getMsg());
							status.isRollbackOnly();
							return null;
						}else if(initialNew.getCurrentorId().intValue()!=sm.getUserId()){
							resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(), InitialErrorsEnum.ERROR_MSG_RECORD_RECEIVE.getMsg());
							status.isRollbackOnly();
							return null;
						}
					}
					initialNew.setMemo(initial.getMemo());
					initialNew.setGmtAccept(initial.getGmtAccept());
					InitialItem initialItem = null;
					map.clear();
					map.put("source", initialItemTemp.getSource());
					map.put("code", initialItemTemp.getCode());
					Part part = partService.getPartByConditions(map);
					if (part == null) {
						resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(), InitialErrorsEnum.ERROR_MSG_NOPART.getMsg());
						return null;
					} else {
							if (initialItemTemp.getId() == null) {//新增
								initialItem = new InitialItem();
							} else if (initialItemTemp.getId() != null) {//修改
								map.clear();
								map.put("id", initialItemTemp.getId());
								map.put("companyId", sm.getCompanyId());
								initialItem = (InitialItem)getDao().getById(map);
							}
							calInitialAmount(initialNew, initialItem, initialItemTemp);//计算initial的总金额
							if (initialItem != null) {
								initialItem.setCode(initialItemTemp.getCode());
								initialItem.setSource(initialItemTemp.getSource());
								initialItem.setStoreId(initialItemTemp.getStoreId());
								initialItem.setStoreName(initialItemTemp.getStoreName());
								initialItem.setBrand(initialItemTemp.getBrand());
								initialItem.setOrigin(initialItemTemp.getOrigin());
								initialItem.setCost(initialItemTemp.getCost());
								initialItem.setRetailPrice(initialItemTemp.getRetailPrice());
								initialItem.setInsurancePrice(initialItemTemp.getInsurancePrice());
								initialItem.setMinPrice(initialItemTemp.getMinPrice());
								initialItem.setQuantity(initialItemTemp.getQuantity());
								initialItem.setShelf(initialItemTemp.getShelf());
								initialItem.setMaxOnHand(initialItemTemp.getMaxOnHand());
								initialItem.setMinOnHand(initialItemTemp.getMinOnHand());
								initialItem.setSwapCode(initialItemTemp.getSwapCode());
								initialItem.setTempName(initialItemTemp.getTempName());
								initialItem.setCarModel(initialItemTemp.getCarModel());
								initialItem.setCostAmount(InitialUtil.calAmout(initialItemTemp));
								initialItem.setPartId(part.getId());
								initialItem.setName(part.getName());
								initialItem.setNameEn(part.getNameEn());
								initialItem.setMeasurementUnit(part.getMeasurementUnit());
								initialItem.setPartCategoryId(part.getPartCategoryId());
								initialItem.setLevel1Name(part.getLevel1Name());
								initialItem.setLevel2Name(part.getLevel2Name());
								initialItem.setLevel1Id(part.getLevel1Id());
								InitialItemErrors.setErrorsProperty(initialItem);
							}						
							initialItem.setInitialId(initialNew.getId());
							if (initialItemTemp.getId() == null) {
								getDao().create(initialItem);
								resultMap.put("opr", "new");
							} else if (initialItemTemp.getId() != null) {
								getDao().update(initialItem);
								resultMap.put("opr", "edit");
							}
							resultMap.put("initialItem", initialItem);
							if(isRetInitial){
								Map<String,Object> inVo=initialService.getInitialVOById(initialNew.getId(),sm);
								resultMap.put("initial",inVo.get("data"));
							}
					}
				}catch(Exception e){
					logger.error("保存一条期初明细出错",e);
					resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(), InitialErrorsEnum.ERROR_MSG_DATABASE.getMsg());
					return null;
				}
				resultMap.put(InitialErrorsEnum.SUCCESS.getMsg(), InitialErrorsEnum.RESULT_TYPE_SUCCESS.getMsg());
				return null;
			}
		});
		return resultMap;
	
	}
	private void calInitialAmount(Initial initial,InitialItem initialItem,InitialItem initialItemTemp){
		if(initialItem.getId()==null){//新建的
			initial.setAmount(initial.getAmount().add(InitialUtil.calAmout(initialItemTemp)));
		}else{//修改的
			initial.setAmount(initial.getAmount().add(InitialUtil.calAmout(initialItemTemp)).subtract(initialItem.getCostAmount()));
		}
		initialService.update(initial);
	}

	public PartService getPartService() {
		return partService;
	}

	public void setPartService(PartService partService) {
		this.partService = partService;
	}

	public InitialService getInitialService() {
		return initialService;
	}

	public void setInitialService(InitialService initialService) {
		this.initialService = initialService;
	}
	
}
